package org.hnzyx.joggle.server;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.hnzyx.joggle.common.CommonVariable;
import org.hnzyx.joggle.exceptions.SignErrorException;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

public class SignDetect {


    public void check(HttpServletRequest req,String url, String getParameter, String postBody) throws UnsupportedEncodingException, SignErrorException {
        // 用户的签名
        String sign = req.getHeader(CommonVariable.SIGN);
        Map<String, String> stringStringMap = this.parameterBuildMap(getParameter, postBody);
        String s = this.formatUrlParam(stringStringMap, "utf-8", false);

        String urlPr = url + CommonVariable.WHAT + s;
        System.out.println(urlPr);
        String md5 = DigestUtils.md5DigestAsHex(urlPr.getBytes());
        if (!md5.equals(sign)){
            throw new SignErrorException();
        }
    }


    // 将参数构建成Map对象 进修参数顺序排序
    public Map<String, String> parameterBuildMap(String getParameter, String postBody){
        Map<String, String> parameterMap = null;
        if (postBody != "" && postBody != null && postBody.length() > 0){
            parameterMap = (Map<String,String>)JSON.parseObject(postBody, Map.class);
        } else {
            parameterMap = new HashMap<String, String>();
        }
        if (getParameter != "" && getParameter != null && getParameter.length() > 0){
            String[] split = getParameter.split("&");
            for (int i = 0; i < split.length; i++) {
                if (split[i] != "") {
                    String[] keyValue = split[i].split("=");
                    if (keyValue.length == 2){
                        parameterMap.put(keyValue[0],keyValue[1]);
                    }
                }
            }
        }
        return parameterMap;
    }

    /**
     * @param param 参数
     * @param encode 编码
     * @param isLower 是否小写
     * @return
     */
    public static String formatUrlParam(Map<String, String> param, String encode, boolean isLower) throws UnsupportedEncodingException {
        String params = "";
        try {
            List<Map.Entry<String, String>> itmes = new ArrayList<Map.Entry<String, String>>(param.entrySet());

            //对所有传入的参数按照字段名从小到大排序
            //Collections.sort(items); 默认正序
            //可通过实现Comparator接口的compare方法来完成自定义排序
            Collections.sort(itmes, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    // TODO Auto-generated method stub
                    return (o1.getKey().toString().compareTo(o2.getKey()));
                }
            });

            //构造URL 键值对的形式
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> item : itmes) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    String val = item.getValue();
                    val = URLEncoder.encode(val, encode);
                    if (isLower) {
                        sb.append(key.toLowerCase() + "=" + val);
                    } else {
                        sb.append(key + "=" + val);
                    }
                    sb.append("&");
                }
            }

            params = sb.toString();
            if (!params.isEmpty()) {
                params = params.substring(0, params.length() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
           throw e;
        }
        return params;
    }



}
